import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:flutter/material.dart';
import 'package:hello_word/common/net/api.dart';

final http = Http();

class Http extends BaseHttp {
  @override
  init() {
    options.baseUrl = "https://www.pgyer.com/apiv2/";
    // cookie持久化 异步
    interceptors
      ..add(AppApiInterceptors())
      ..add(CookieManager(PersistCookieJar(dir: "")));
  }
}

class AppApiInterceptors extends InterceptorsWrapper {
  @override
  Future onRequest(RequestOptions options) async {
    options.queryParameters["_api_key"] = "00f25cece8e201753872c268b5832df9";
    options.queryParameters["appKey"] = "0f7026d9c95933c7d0553628605b6ea4";
    debugPrint('---api-request--->url--> ${options.baseUrl}${options.path}' +
        ' queryParameters: ${options.queryParameters}');
    return options;
  }

  @override
  Future onResponse(Response response) async {
    ResponseData responseData = ResponseData.fromjson(response.data);
    if (responseData.success) {
      response.data = responseData.data;
      return http.resolve(response);
    } else {
      if (responseData.code == -1001) {
        // 如果cookie过期,需要清除本地存储的登录信息
        // StorageManager.localStorage.deleteItem(UserModel.keyUser);
        throw const UnAuthorizedException(); // 需要登录
      } else {
        throw NotSuccessException.fromRespData(responseData);
      }
    }
  }
}

class ResponseData extends BaseResponseData {
  @override
  bool get success => code == 0;

  ResponseData.fromjson(Map<String, dynamic> json) {
    code = json['code'];
    message = json['message'];
    data = json['data'];
  }
}
